<?php

declare(strict_types=1);

namespace App\Command;

use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputArgument;

require_once(BASE_PATH . '/app/Libs/Helper.php');

/**
 * 域名对应组号检查
 */
#[Command]
class DomainCommand extends HyperfCommand
{
    protected $logger;
    protected $config;

    public function __construct(StdoutLoggerInterface $logger, ConfigInterface $config)
    {
        $this->logger = $logger;
        $this->config = $config;

        // 定义命令行名称
        parent::__construct('domain');
    }

    public function configure()
    {
        parent::configure();
        $this->addArgument('domains', InputArgument::REQUIRED, '域名');
        $this->setDescription('域名对应组号检查');
    }

    public function handle()
    {
        $domains = $this->input->getArgument('domains') ?? '';
        $domains = explode(',', $domains);
        $container = ApplicationContext::getContainer();
        $guzzle = $container->get(\Hyperf\Guzzle\ClientFactory::class);

        foreach ($domains as $k => $dm) {
//            $resp=@shell_exec('/www/server/pyporject_evn/GroupcheckMaster_venv/bin/python3 /www/wwwroot/GroupcheckMaster/groupcheck.py '.$dm);
//            $resp=str_replace(["\n", "\r", "\t", ' '], '', $resp);
//            var_dump($resp);
//            return \Hyperf\Command\Command::SUCCESS;

            $kaitou = $dm;
            if (!str_starts_with($dm, 'http')) {
                $kaitou = 'http://' . $dm;
            }

            try {
                $resp = @$guzzle->create([
                    'connect_timeout' => 5,
                    'timeout' => 10,
                    'verify' => false,
                    'http_errors' => false,
                    'allow_redirects' => true, // 默认最多5词的重定向
                    'headers' => [
                        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
                    ],
                ])->request('GET', rtrim($kaitou, '/') . '/sxallsitemap.xml');
                $code = intval(@$resp->getStatusCode());
                $htmlBody = strtolower((string)$resp->getBody());

                if ($code === 200) {
                    $ret = 'failure';
                    $body = '请手动排查';
                    $bodyInit = $body;
                    $htmlBody2 = '--';
                    if (mb_strlen($htmlBody) < 50) {
                        $htmlBody2 = str_replace(["\n", "\r", "\t", ' '], '', $htmlBody);
                    }
                    if (str_starts_with($htmlBody, 'ok')) {
                        $ret = 'success';
                        $body = $htmlBody;
                    } elseif (str_contains($htmlBody, 'verifying that you are not a robot')) {
                        $body = '被判定为机器人，请手动访问';
                    } elseif (str_contains($htmlBody, 'bandwidth limit exceeded')) {
                        $body = '被判定高危站点，请手动访问';
                    } elseif (str_contains($htmlBody, 'page cannot be displayed')) {
                        $body = '被判定隐私站，请手动访问';
                    } elseif (str_contains($htmlBody, '401 unauthorized')) {
                        $body = '要账号密码登录';
                    } elseif (str_contains($htmlBody, '403 forbidden')) {
                        $body = '访问被拒绝';
                    } elseif (str_contains($htmlBody, 'account suspended') || str_contains($htmlBody, 'account temporary on hold')) {
                        $body = '账号被停用';
                    } elseif (str_contains($htmlBody, 'planethoster - suspendu')) {
                        $body = '站点被停用';
                    } elseif (str_contains($htmlBody, 'internal server error')) {
                        $body = '服务端错误';
                    } elseif (str_contains($htmlBody, 'please wait while your request is being verified')) {
                        $body = '要手动验证';
                    } elseif (str_contains($htmlBody, 'page not found') || str_contains($htmlBody, '<title>404 not found</title>')) {
                        $body = '网页不存在';
                    } elseif (str_contains($htmlBody, 'under construction') || str_contains($htmlBody, '<title>coming soon</title>')) {
                        $body = '空站点'; // 网站建设中
                    } elseif (str_contains($htmlBody, ' lang="en"') || str_contains($htmlBody, ' lang="es"')
                        || str_contains($htmlBody, ' lang="pt-br"') || str_contains($htmlBody, ' lang="fa"')
                        || str_contains($htmlBody, ' lang="en-us"') || str_contains($htmlBody, 'html lang="ru"')
                        || str_contains($htmlBody, ' lang="en-au"') || str_contains($htmlBody, 'html lang="fr-fr"')
                        || str_contains($htmlBody, '<head><script>function set_cookie(){var')
                        || str_contains($htmlBody, 'charset=iso-8859-1')
                        || str_contains($htmlBody, '<body><script type=\'text/javascript\'>window.location.replace')
                        || str_contains($htmlBody, '<head><script>window.onload=function(){window.location.href=')
                    ) {
                        $body = '劫持掉了';
                    } elseif (empty($htmlBody) || empty($htmlBody2) || str_contains($htmlBody, 'you need to enable javascript to run this app')) {
                        $body = '空页面';
                    } elseif (str_contains($htmlBody, '<b>fatal error</b>') || str_contains($htmlBody, 'parse error: syntax error in') || str_contains($htmlBody, '<b>warning</b>:  ')) {
                        $body = '网站有错误';
                    } elseif (!empty($htmlBody)) {
                        $count1 = substr_count($htmlBody, '.xml');
                        $count2 = substr_count($htmlBody, '<url>');
                        if ($count1 > 10 || $count2 > 30) {
                            $body = '同行占领-XML';
                        }
                        if ($body === $bodyInit && str_contains($htmlBody, '<title>') && str_contains($htmlBody, '<meta') && (str_contains($htmlBody, ' lang="ja"') || str_contains($htmlBody, 'content="ja_jp"')) && (str_contains($htmlBody, '円') || str_contains($htmlBody, '¥'))) {
                            $body = '同行占领-商品页';
                        }
                        if ($body === $bodyInit && str_contains($htmlBody, 'website unavailable')) {
                            $body = '网站不可用';
                        }
                    }
                } elseif ($code === 301) {
                    $ret = 'failure';
                    $body = '永久重定向';
                } elseif ($code === 302) {
                    $ret = 'failure';
                    $body = '临时重定向';
                } elseif ($code === 401) {
                    $ret = 'failure';
                    $body = '访问被拒绝';
                } elseif ($code === 403) {
                    $ret = 'failure';
                    $body = '访问被拒绝';
                } elseif ($code === 404) {
                    $ret = 'failure';
                    $body = '网页不存在';
                } elseif ($code >= 500) {
                    $ret = 'failure';
                    $body = '服务端错误';
                } elseif ($code === 0) {
                    $ret = 'failure';
                    $body = '异常-请管理员排查';
                } else {
                    $ret = 'failure';
                    $body = '请手动排查';
                }

                // var_dump(mb_substr($htmlBody, 0, 500), $code, $body);
                // return \Hyperf\Command\Command::SUCCESS;

                $this->line($k . '=' . json_encode(['domain' => $dm, 'ret' => $ret, 'body' => $body], JSON_UNESCAPED_UNICODE));
            } catch (\Throwable $e) {
                $ret = 'failure';
                $emsg = $e->getMessage();
                if ($emsg === 'Connection reset by peer') {
                    $emsg = '请手动排查-2';
                }
                $this->line($k . '=' . json_encode(['domain' => $dm, 'ret' => $ret, 'body' => $emsg], JSON_UNESCAPED_UNICODE));
            }
        }

        $this->line('=====》程序退出');
        return \Hyperf\Command\Command::SUCCESS;
    }
}
